const triggerUpload = document.getElementById('triggerUpload');
const filePickerContainer = document.getElementById('filePickerContainer');
const customFileButton = document.getElementById('customFileButton');
const fileInput = document.getElementById('fileInput');
const fileName = document.getElementById('fileName');
const uploadButtonContainer = document.getElementById('uploadButtonContainer');
const cancelUploadButton = document.getElementById('cancelUploadButton');
const cancelUploadContainer = document.getElementById('cancelUploadContainer');
let ws = null;
// fileInput.addEventListener('change', () => {
//     if (fileInput.files.length > 0) {
//         fileNameDisplay.textContent = "已选择文件: " + fileInput.files[0].name;
//     } else {
//         fileNameDisplay.textContent = "未选择文件";
//     }
// });


// 点击“上传文件”按钮，显示“选择文件”按钮
triggerUpload.addEventListener('click', () => {
    triggerUpload.style.display = 'none';
    filePickerContainer.classList.remove('hidden');
    fileInput.click();  // 自动触发隐藏的文件选择框
    console.log("你好");
    cancelUploadContainer.classList.remove('hidden');
});

// 点击“选择文件”按钮，触发文件选择
customFileButton.addEventListener('click', () => {
    fileInput.click();
});

// 文件选择完成后，显示文件名，并显示“开始上传”按钮
fileInput.addEventListener('change', () => {
    if (fileInput.files.length > 0) {
        fileName.textContent = "已选择文件: " + fileInput.files[0].name;
        uploadButtonContainer.classList.remove('hidden');
        cancelUploadContainer.classList.remove('hidden');
    }
});

cancelUploadButton.addEventListener('click', () => {
    filePickerContainer.classList.add('hidden');
    uploadButtonContainer.classList.add('hidden');
    cancelUploadContainer.classList.add('hidden');
    fileName.textContent = "未选择文件";
    triggerUpload.style.display = 'block';
})


function initWebSocket() {
    const host = window.location.host;
    const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
    const wsUrl = protocol + host + '/processpdf';
    ws = new WebSocket(wsUrl);

    ws.onmessage = function (event) {
        const data = JSON.parse(event.data);

        if (data.task && data.message) { // 确保数据包含任务和消息
            const taskElement = document.getElementById(data.task);
            if (taskElement) {
                // taskElement.textContent = data.message;

                const indicator = taskElement.querySelector('.status-indicator');
                const statusText = taskElement.querySelector('.status-text');

                // 清除所有状态类
                indicator.className = 'status-indicator';
                statusText.className = 'status-text';

                // 根据状态更新
                if (data.status === 'pending') {
                    indicator.classList.add('status-pending');
                    indicator.innerHTML = '<i class="fas fa-clock"></i>';
                    statusText.classList.add('pending-text');
                    statusText.textContent = data.message;
                } else if (data.status === 'running') {
                    indicator.classList.add('status-running');
                    indicator.innerHTML = '<i class="fas fa-sync-alt fa-spin"></i>';
                    statusText.classList.add('running-text');
                    statusText.textContent = data.message;
                } else if (data.status === 'done') {
                    indicator.classList.add('status-done');
                    indicator.innerHTML = '<i class="fas fa-check"></i>';
                    statusText.classList.add('done-text');
                    statusText.textContent = data.message;

                    // 存储结果
                    // taskResults[functionId] = result;
                    // updateResults();
                } else if (data.status === 'error') {
                    indicator.classList.add('status-error');
                    indicator.innerHTML = '<i class="fas fa-times"></i>';
                    statusText.classList.add('error-text');
                    statusText.textContent = data.message;
                }
            }
        }
    };

    ws.onerror = function (error) {
        console.log('WebSocket Error:', error);
    };
}

function startUpload() {
    const file = fileInput.files[0];
    if (!file) {
        alert("请先选择文件");
        return;
    }
    const formData = new FormData();
    formData.append('upload_file', file);
    formData.append('knowbase_name', KNOWBASE_NAME)
    fetch(FILE_UPLOAD_URI, {
        method: 'POST',
        body: formData
    }).then(response => response.json())
        .then(
            data => {
                if (data.statusCode === 200) {
                    alert(data.message);
                    // location.reload();
                    data.taskCode = 'start';
                    initWebSocket();
                    const sendWhenOpen = () => {
                        if (ws.readyState === WebSocket.OPEN) {
                            ws.send(JSON.stringify(data)); // ✅ 必须 stringify
                        } else {
                            setTimeout(sendWhenOpen, 100); // 等待连接
                        }
                    };
                    sendWhenOpen();
                    // ws.send(JSON.stringify(data));
                } else {
                    alert(data.message);
                }
            })

        .catch(error => {
            console.error('Error:', error);
            alert('发生错误，请查看日志');
        });
}

//绑定点击事件
document.getElementById('startUploadButton').addEventListener('click', startUpload);